<template>
    <div class="contentPage">
        <div class="pageTitle">店铺列表</div>
        <Search :data="params.searchData" @search="getSearch"/>
        <div class="tableBox">

           <div style="display: flex;justify-content: flex-end;align-items: center">
               <div style="margin-right: 12px;color: #1677ff;">
                   <VerticalAlignBottomOutlined />
                   <a href="/storage/files/示例文件.xlsx" download>下载示例文件</a>
               </div>
               <a-button type="primary" @click="addCustomer" style="margin-left: 12px">
                   <PlusOutlined/>
                   新建店铺
               </a-button>
           </div>
            <a-table style="margin-top: 12px" :dataSource="params.dataSource" :columns="params.columns" row-key="id"
                     :scroll="{ x: 1600 }"
                     :pagination="false">
                <template #bodyCell="{ column, text, record }">
                    <template v-if="column.dataIndex === 'status'">
                        <div :style="record.status === 0 ? 'color:red':''">{{record.status === 1 ? '正常' : '未上线'}}</div>
                    </template>
                    <template v-if="column.dataIndex === 'operation'">
                        <div style="display: flex;">
                            <div class="linkBtn" style="margin-right: 12px" @click="entry(record)">数据修正</div>
                            <UploadFile :value="params.formState.wonerCreditImage" text="数据导入" :showText="true" :showUploadList="true" :saveName="true" @getImageUrl="e=>getFileUrls(e,record)" />
                            <div class="linkBtn" style="margin-left: 12px" @click="edit(record,1)">编辑</div>
                            <a-popconfirm
                                placement="left"
                                title="确认删除?"
                                ok-text="是"
                                cancel-text="否"
                                @confirm="confirmRemove(record)"
                            >
                                <div class="linkBtn" style="margin-left: 12px">
                                    删除
                                </div>
                            </a-popconfirm>
                            <a-popconfirm
                                placement="left"
                                :title="'确认'+(record.status === 0 ?'上线':'下线')+'?'"
                                ok-text="是"
                                cancel-text="否"
                                @confirm="confirmFreeze(record)"
                            >
                                <div class="linkBtn"  :style="record.status === 1 ? 'color:red;margin-left: 12px':'margin-left: 12px'">
                                    {{ record.status === 0 ?'上线':'下线' }}
                                </div>
                            </a-popconfirm>
                        </div>
                    </template>
                </template>
            </a-table>
            <a-pagination style="margin-top: 12px" show-size-changer v-model:current="params.page"
                          :total="params.total" @showSizeChange="onShowSizeChange" @change="onShowPageChange"/>
        </div>
        <a-modal v-model:open="params.visible" :title="params.editId ? '编辑店铺' : '新建店铺'" @ok="handleOk" destroyOnClose width="700px">
            <a-form
                :model="params.formState"
                name="basic"
                ref="formRef"
                style="margin-top: 24px"
                :label-col="{ span: 4 }"
                :wrapper-col="{ span: 20 }"
                autocomplete="off"
            >
                <a-form-item label="店铺名称" name="merchantNo" required>
                    <div style="display: flex;align-items: center;white-space: nowrap;">
                        <a-select v-model:value="params.formState.merchantNo" show-search>
                            <a-select-option v-for="(item,index) in params.storeList" :key="index" :value="item.merchant_no">{{item.name}}</a-select-option>
                        </a-select>
                        <div class="linkBtn" style="margin-left: 12px" @click="uploadStore()">刷新</div>
                    </div>
                </a-form-item>
                <a-form-item label="所属项目" name="projectId" required>
                    <a-select v-model:value="params.formState.projectId" show-search>
                        <a-select-option v-for="(item,index) in params.projectList" :key="index" :value="item.id">{{item.name}}</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="出资总额" name="money" required>
                    <a-input-number style="width: 100%" v-model:value="params.formState.money" addon-after="元"></a-input-number>
                </a-form-item>
                <a-form-item label="联营开始时间" name="showDate">
                    <a-date-picker style="width: 100%" v-model:value="params.formState.showDate" value-format="YYYY-MM-DD"/>
                </a-form-item>

                <a-form-item label="关联资方" name="capitalIds" required>
                    <a-table :columns="params.addColumns" :dataSource="params.formState.capitalIds" rowKey="id" :pagination="false">
                        <template #bodyCell="{ column, text, record, index }">
                            <template v-if="column.dataIndex === 'capitalId'">
                                <a-select v-model:value="record.capitalId" show-search style="width: 180px">
                                    <a-select-option v-for="(item,idx) in params.capitalList" :key="idx" :value="item.id">{{item.name}}</a-select-option>
                                </a-select>
                            </template>
                            <template v-if="column.dataIndex === 'money'">
                                <a-input-number v-model:value="record.money" :disabled="!params.formState.money" style="width: 180px" :min="0.01" :max="params.formState.money"></a-input-number>
                            </template>
                            <template v-if="column.dataIndex === 'operation'">
                                <div style="display: flex;">
                                    <div class="linkBtn" @click="capitalIdChange(record,1)">添加</div>
                                    <a-popconfirm
                                        placement="left"
                                        title="确认删除?"
                                        ok-text="是"
                                        cancel-text="否"
                                        v-if="index>0"
                                        @confirm="capitalIdChange(index,2)"
                                    >
                                        <div class="linkBtn" style="margin-left: 12px">
                                            删除
                                        </div>
                                    </a-popconfirm>
                                </div>
                            </template>
                        </template>
                    </a-table>
                </a-form-item>
                <a-form-item label="收益比例" name="incomeRate" required>
                    <a-input-number style="width: 100%" v-model:value="params.formState.incomeRate" addon-after="%"></a-input-number>
                </a-form-item>
                <a-form-item label="分账比例" name="subAccountRate" required>
                    <a-input-number style="width: 100%" v-model:value="params.formState.subAccountRate" addon-after="%"></a-input-number>
                </a-form-item>
                <a-form-item label="预计回本周期" name="endBackDate" required>
                    <a-input-number style="width: 100%" v-model:value="params.formState.endBackDate" addon-after="月"></a-input-number>
                </a-form-item>

                <a-form-item label="店铺联系人" name="contacter" required>
                    <a-input v-model:value="params.formState.contacter"></a-input>
                </a-form-item>
                <a-form-item label="店铺联系电话" name="phone" required>
                    <a-input v-model:value="params.formState.phone"></a-input>
                </a-form-item>
                <a-form-item label="店铺地址" name="addr" required>
                    <a-input v-model:value="params.formState.addr"></a-input>
                </a-form-item>
                <a-form-item label="邮箱地址" name="email">
                    <a-input v-model:value="params.formState.email"></a-input>
                </a-form-item>
                <a-form-item label="营业执照" name="businessLicenseImage">
                    <Upload :value="params.formState.businessLicenseImage" @getImageUrl="e=>getImageUrl(e,'businessLicenseImage')"/>
                </a-form-item>
                <a-form-item label="其它店铺信息" name="otherFileUrl">
                    <div v-for="(item,index) in params.formState.otherFileUrl" :key="index" style="display: flex;align-items: flex-start;flex-wrap: wrap;justify-content: flex-start;margin-bottom: 12px">
                        <a-input v-model:value="item.fileText" placeholder="输入店铺信息内容" style="width: 280px"></a-input>
                        <UploadFile style="width: 130px;margin: 0 12px" :value="item.file" :saveName="true" @getImageUrl="e=>getFileUrl(e,'otherFileUrl',index)"  @removeImageUrl="e=>removeFileUrl(e,'otherFileUrl',index)" />
                        <div class="linkBtn btnText" @click="addAndRemove(1,index)">添加</div>
                        <div class="linkBtn btnText" v-if="params.formState.otherFileUrl.length > 1" style="margin-left: 12px" @click="addAndRemove(2,index)">删除</div>
                    </div>
                </a-form-item>
            </a-form>
        </a-modal>
        <a-modal v-model:open="params.entryVisible" title="录入" destroyOnClose width="500px" @ok="entrySubmit()" okText="已收款">
            <a-form
                :model="params.entryRecord"
                name="basic"
                ref="formRef"
                style="margin-top: 24px"
                :label-col="{ span: 4 }"
                :wrapper-col="{ span: 20 }"
                autocomplete="off"
            >
                <a-form-item label="店铺名称" name="merchantNo">
                    <div>{{params.entryRecord?.mall?.name}}</div>
                </a-form-item>
                <a-form-item label="日期选择" name="date">
                    <a-range-picker v-model:value="params.entryRecord.date" :format="['YYYY-MM-DD','YYYY-MM-DD']" value-format="YYYY-MM-DD" />
                    <a-button type="primary" style="margin-left: 12px" @click="searchClick()">查询</a-button>
                </a-form-item>
                <a-form-item label="分账金额" name="subamount">
                    <div>{{params.entryRecord?.subamount}}</div>
                </a-form-item>
                <a-form-item label="应结金额" name="income">
                    <div>{{params.entryRecord?.income}}</div>
                </a-form-item>
                <a-form-item label="实收差异" name="diffamount">
                    <div>{{params.entryRecord?.diffamount}}</div>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>
<script setup>
import {onMounted, reactive, ref} from 'vue'
import {PlusOutlined,VerticalAlignBottomOutlined} from '@ant-design/icons-vue'
import {
    queryDiffRange,
    capitalList,
    getMalls, mallAdd, mallDelete,
    mallList,
    mallUpdate,
    projectList,
    updateMalls, diffRangeSave, recordByHandle
} from '../../../api/project.js'
import Search from '../../../components/search/index.vue'
import Upload from "@/admin/components/upload/index.vue";
import UploadFile from "@/admin/components/uploadFile/index.vue";
import {message} from "ant-design-vue";


const formRef = ref(null)
const params = reactive({
    visible: false,
    entryVisible: false,
    entryRecord: null,
    editId: '',
    page: 1,
    pageSize: 10,
    total: 11,
    formState: {
        otherFileUrl:[{fileText:'',file:[],name:''}]
    },
    searchData: [
        {name: '店铺编号', type: 'input', val: '', key: 'mallNo'},
        {name: '店铺名称', type: 'select', val: '', key: 'merchantNo'},
        {name: '资方名称', type: 'select', val: '', key: 'capitalId'},
        {name: '出资金额', type: 'maxMin', val: '', key: ['moneyLeft','moneyRight']},
        {name: '收益比例%', type: 'maxMin', val: '', key: ['incomeRateLeft','incomeRateRight']},
        {name: '分账比例%', type: 'maxMin', val: '', key: ['subAccountRateLeft','subAccountRateRight']},
        {name: '新建时间', type: 'picker', val: [], key: ['createdAtLeft', 'createdAtRight']},
    ],
    searchVal: {},
    dataSource: [],
    columns: [
        {title: '店铺编号', dataIndex: 'mall_no', key: 'mall_no'},
        {title: '店铺名称', dataIndex: 'mall', key: 'mall',width: 220,  customRender: ({text, record}) => {
                return text?.name
            }},
        {title: '资方名称', dataIndex: 'capitalName', key: 'capitalName',width: 220},
        {title: '出资金额(元)', dataIndex: 'money', key: 'money'},
        {title:'联营开始日期 ',dataIndex: 'show_date', key: 'show_date'},
        {title: '收益比例', dataIndex: 'income_rate', key: 'income_rate'},
        {title: '分账比例', dataIndex: 'sub_account_rate', key: 'sub_account_rate'},
        {title: '所属项目', dataIndex: 'project', key: 'project',  customRender: ({text, record}) => {
                return text?.name
            }},
        {title: '状态', dataIndex: 'status', key: 'status'},
        {title: '新建时间', dataIndex: 'created_at', key: 'created_at'},
        {title: '操作', dataIndex: 'operation', key: 'operation',width: 230, fixed: 'right'},
    ],
    addDataSource:[],
    addColumns: [
        {title: '* 资方名称', dataIndex: 'capitalId', key: 'capitalId'},
        {title: '* 出资金额（元）', dataIndex: 'money', key: 'money'},
        {title: '操作', dataIndex: 'operation', key: 'operation',width: 150},
    ],
    storeList: [],
    capitalList: [],
    projectList:[]
})
onMounted(() => {
    getList()
    capitalList({page: 1, pageSize: 100000}).then(res => {
        let data = res.data.items
        params.capitalList = data
        params.searchData.map(item => {if(item.key === 'capitalId') item.data = data})
    })
    getStore()
    projectList({page: 1, pageSize: 100000}).then(res => {
        params.projectList = res.data.items
    })
})
const getFileUrls = (e,record) => {
    recordByHandle({fileUrl: e.file, id: record.id}).then(res => {
        if (res?.code === 200) {
            getList()
            message.success(res.message)
        } else {
            message.error(res.message)
        }
    })
}
const getDates = () => {
    let newDay = new Date()
    let today = new Date(newDay.getTime() - 2 * 24 * 60 * 60 * 1000);
    let sevenDaysAgo = new Date(newDay.getTime() - 9 * 24 * 60 * 60 * 1000);

    let year = today.getFullYear();
    let month = String(today.getMonth() + 1).padStart(2, '0');
    let day = String(today.getDate()).padStart(2, '0');
    let formattedToday = `${year}-${month}-${day}`;

    let sevenDaysYear = sevenDaysAgo.getFullYear();
    let sevenDaysMonth = String(sevenDaysAgo.getMonth() + 1).padStart(2, '0');
    let sevenDaysDay = String(sevenDaysAgo.getDate()).padStart(2, '0');
    let formattedSevenDaysAgo = `${sevenDaysYear}-${sevenDaysMonth}-${sevenDaysDay}`;

    return [formattedSevenDaysAgo,formattedToday]
}
const searchClick = () => {
    queryDiffRange({id: params.entryRecord.id,timeLeft:params.entryRecord.date[0],timeRight:params.entryRecord.date[1]}).then(res=>{
        params.entryRecord.income = res.data.income
        params.entryRecord.subamount = res.data.subamount
        params.entryRecord.diffamount = res.data.diffamount
    })
}
const entry = (record) => {
    record.date = getDates()
    params.entryRecord = record
    searchClick()
    params.entryVisible = true
}
const entrySubmit = () => {
    diffRangeSave({id: params.entryRecord.id,timeLeft:params.entryRecord.date[0],timeRight:params.entryRecord.date[1]}).then(res=>{
        if (res?.code === 200) {
            getList()
            params.entryVisible = false
            message.success(res.message)
        } else {
            message.error(res.message)
        }
    })
}
const getStore = () => {
    getMalls({page: 1, pageSize: 100000}).then(res => {
        let data = res.data
        params.storeList = data
        let searchData = JSON.parse(JSON.stringify(data))
        searchData.map(item => {item.id = item.merchant_no})
        params.searchData.map(item => {if(item.key === 'merchantNo') item.data = searchData})
    })
}
const onShowPageChange = (page) => {
    params.page = page
    getList()
}
const onShowSizeChange = (current, pageSize) => {
    params.pageSize = pageSize;
    getList()
}
const getList = () => {
    let data = {
        ...params.searchVal,
        page: params.page,
        pageSize: params.pageSize,
    }
    mallList(data).then(res => {
        res.data.items.map(item => {
            let config = []
            item.capital_rel.map(d=>{
                console.log(item.money , d.money)
                config.push(d.capital.name+'（'+((d.money / item.money) * 100).toFixed(2)+'%）')
            })
            item.capitalName = config.join(',')
        })
        params.dataSource = res.data.items
        params.total = res.data.total
    })
}
const openModal = () => {
    params.visible = true
}
const addCustomer = () => {
    params.formState.capitalIds = [
        {
            capitalId:'',
            money:''
        }
    ]
    params.formState.subDate = ''
    params.formState.merchantNo = ''
    params.formState.projectId = ''
    params.formState.money = ''
    params.formState.incomeRate = ''
    params.formState.subAccountRate = ''
    params.formState.contacter = ''
    params.formState.phone = ''
    params.formState.email = ''
    params.formState.showDate = ''

    params.formState.addr = ''
    params.formState.businessLicenseImage = ''
    params.formState.otherFileUrl = [{fileText:'',file:[],name:''}]
    openModal()
}
const addAndRemove = (type,index) => {
    if(type === 1){
        params.formState.otherFileUrl.push({fileText:'',file:[],name:''})
    }else{
        params.formState.otherFileUrl.splice(index,1)
    }
}
const removeFileUrl = (e,key,index) => {
    if(index>=0){
        params.formState[key][index] = e
    }else{
        params.formState[key] = e
    }
}
const getFileUrl = (e,key,index) => {
    if(index>=0){
        if(!params.formState[key][index]) params.formState[key][index] = []
        params.formState[key][index].file = [e]
    }else{
        if(!params.formState[key]) params.formState[key] = []
        params.formState[key] = [e]
    }
}
const getImageUrl = (e,key) => {
    params.formState[key] = e
}
const edit = (item) => {
    params.editId = item.id
    params.formState.merchantNo = item.merchant_no
    params.formState.projectId = item.project?.id || ''
    params.formState.money = item.money
    params.formState.incomeRate = item.income_rate
    params.formState.subAccountRate = item.sub_account_rate
    params.formState.endBackDate = item.end_back_date
    params.formState.contacter = item.contacter
    params.formState.phone = item.phone
    params.formState.email = item.email
    params.formState.addr = item.addr
    params.formState.showDate = item.show_date
    // params.formState.businessLicenseImage = item.business_license_image ? item.business_license_image[0] :''
    params.formState.capitalIds = item.capital.map(d=>d.id)
    params.formState.otherFileUrl = item.other_file_url || [{fileText:'',file:[],name:''}]

    params.formState.subDate = item.mall.sub_date
    params.formState.businessLicenseImage = item.business_license_image ? item.business_license_image[0] :''
    // params.formState.capitalIds = item.capital.map(d=>d.id)
    let config = []
    item.capital_rel.map(item=>{
        config.push({
            money: item.money,
            capitalId: item.capital.id
        })
    })
    params.formState.capitalIds = config
    openModal()
}
const uploadStore = () => {
    updateMalls().then(res=>{
        message.success('刷新成功')
        getStore()
    })
}
const confirmRemove = (record) => {
    mallDelete({ids:[record.id]}).then(res=>{
        if (res?.code === 200) {
            getList()
            message.success(res.message)
        } else {
            message.error(res.message)
        }
    })
}
const capitalIdChange = (e,index) => {
    if(index === 1) {
        params.formState.capitalIds.push({
            capitalId:'',
            money:''
        })
    }else{
        params.formState.capitalIds.splice(e,1)
    }
}
const confirmFreeze = (record) =>{
    mallUpdate({ids:[record.id],status: record.status === 0 ? 1 : 0}).then(res=>{
        if (res?.code === 200) {
            getList()
            message.success(res.message)
        } else {
            message.error(res.message)
        }
    })
}
const handleOk = () => {
    let config = JSON.parse(JSON.stringify(params.formState))
    config.businessLicenseImage = config.businessLicenseImage ?[config.businessLicenseImage] : []
    formRef.value.validate().then(() => {
        let nextFlag = false
        params.formState.capitalIds.map(item=>{
            if(!item.money || !item.capitalId) nextFlag = true
        })
        if(nextFlag) return message.success('完善关联资方信息')
        if(params.editId) {
            config.id = params.editId
        }

        mallAdd(config).then(res => {
            if (res?.code === 200) {
                params.visible = false
                getList()
                message.success(res.message)
            } else {
                message.error(res.message)
            }
        })
    })

}
const getSearch = (e) => {
    params.searchVal = e
    getList()
}
</script>
<style scoped lang="less">
@import "./style.less";
</style>
